/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.ytbolg.mcxa.util;

import java.awt.HeadlessException;
import net.ytbolg.mcxa.Launcher.GameInfo;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import net.ytbolg.mcxa.LangAndConfig.Lang;
import net.ytbolg.mcxa.LangAndConfig.LangFile;
import static net.ytbolg.mcxa.Launcher.GameInfo.tpf;
import static net.ytbolg.mcxa.util.ForgeCheck.ReadFile;
//import static net.ytbolg.mcxa.MCLaucherXA.ReadFile;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Ytong
 */
public class Updater extends javax.swing.JFrame {

    public static String DownloadURL = "";
    public static String ver = "";

    /**
     * Creates new form Updater
     */
    public Updater() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel6 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jLabel1.setText("最新版本");

        jLabel2.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jLabel2.setText("当前版本");

        jLabel3.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jLabel3.setText("升级说明：");

        jTextArea1.setEditable(false);
        jTextArea1.setColumns(20);
        jTextArea1.setFont(new java.awt.Font("微软雅黑", 0, 13)); // NOI18N
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jLabel4.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jLabel4.setText("jLabel4");

        jLabel5.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jLabel5.setText("jLabel5");

        jButton1.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N
        jButton1.setText("升级");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("微软雅黑", 0, 12)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 404, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel5)
                                .addGap(18, 18, 18)
                                .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel4)
                                .addGap(110, 110, 110)
                                .addComponent(jLabel6)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton1)))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel4)
                            .addComponent(jLabel6))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2)
                                .addComponent(jLabel5))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(1, 1, 1)
                        .addComponent(jButton1)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(28, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        try {
            setTitle(Lang.getLang("Up_Title"));
            jLabel1.setText(Lang.getLang("Up_Label_newestVer"));
            jLabel2.setText(Lang.getLang("Up_Label_nowVer"));
            jLabel3.setText(Lang.getLang("Up_Label_newSm"));
            jButton1.setText(Lang.getLang("Up_Button_Download"));
            JSONObject jo = new JSONObject(downloadFile("http://ytbolg.net/mcxa/update.json"));
            jLabel4.setText(jo.getString("newVersion"));
            jLabel5.setText(LangFile.Version);
            if (jLabel4.getText().equals(jLabel5.getText())) {
                jButton1.setEnabled(false);
            }
            jTextArea1.setText(jo.getString("shuoming"));
            DownloadURL = jo.getString("DownloadURL");
            ver = jo.getString("newVersion");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_formWindowOpened

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Do.l = jLabel6;
        Do.b = jButton1;
        Do.jpb = jProgressBar1;
        new Thread(new Do()).start();
        jButton1.setEnabled(false);
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public javax.swing.JButton jButton1;
    public javax.swing.JLabel jLabel1;
    public javax.swing.JLabel jLabel2;
    public javax.swing.JLabel jLabel3;
    public javax.swing.JLabel jLabel4;
    public javax.swing.JLabel jLabel5;
    public javax.swing.JLabel jLabel6;
    public javax.swing.JProgressBar jProgressBar1;
    public javax.swing.JScrollPane jScrollPane1;
    public javax.swing.JTextArea jTextArea1;
    // End of variables declaration//GEN-END:variables
public static boolean NeedUpdate() {

        try {
            JSONObject jo = new JSONObject(downloadFile("http://ytbolg.net/mcxa/update.json"));

            return !LangFile.Version.equals(jo.getString("newVersion"));
        } catch (Exception ex) {
            new net.ytbolg.mcxa.Output.Logger(0).Log("Check Update Faild!");
            Logger.getLogger(Updater.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
        // return false;
    }

    public static String downloadFile(String remoteFilePath) throws IOException {

        URL urlfile = null;
        HttpURLConnection httpUrl = null;
        BufferedInputStream bis = null;
        //  BufferedOutputStream bos = null;
        File f = new File(GameInfo.Rundir + GameInfo.tpf + "temp.tmp");
        File xxxx = new File(f.getParent());
        xxxx.mkdirs();

//      f.mkdirs();
        try {
            StringBuilder sb = new StringBuilder();
            urlfile = new URL(remoteFilePath);
            httpUrl = (HttpURLConnection) urlfile.openConnection();
            httpUrl.connect();
            //   bis = new BufferedInputStream(httpUrl.getInputStream());
            InputStreamReader isr = new InputStreamReader(httpUrl.getInputStream());
            //    bos = new BufferedOutputStream(new FileOutputStream(f));
            int len = 0;
            //byte[] b = new byte[len];
            while ((len = isr.read()) != -1) {
                //        bos.write(b, 0, len);
                sb.append((char) len);
            }
         //   bos.flush();
            isr.close();
// bis.close();
            httpUrl.disconnect();
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }

    }
}

class Do implements Runnable {

    public static JLabel l;
    public static JButton b;
    public static JProgressBar jpb;

    public void run() {
        try {
            URLConnection u = (new URL(Updater.DownloadURL)).openConnection();
            HttpURLConnection huc = (HttpURLConnection) u;
            InputStream bis = huc.getInputStream();
            File f = new File(GameInfo.Rundir + tpf + "MCLaucherXA" + Updater.ver + ".jar");
            if (!f.exists()) {
                f.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(f);
            jpb.setMaximum(u.getContentLength());
            jpb.setValue(0);
            int len = 2048;
            byte[] byt = new byte[len];
            int i = 0;
            while ((len = bis.read(byt)) != -1) {
                i = i + len;
                jpb.setValue(i);
                l.setText(i / 1024 + "/" + (u.getContentLength() / 1024) + "KB");
                fos.write(byt, 0, len);
            }

            fos.close();
            bis.close();
            JOptionPane.showMessageDialog(null, Lang.getLang("Up_Box_DownSucc") + "MCLaucherXA" + Updater.ver + ".jar");
            b.setEnabled(true);
            File f2 = new File(GameInfo.Rundir + tpf + "update.note");
            if (f2.exists()) {
                f2.delete();
            }
            f2.createNewFile();
            FileWriter fw = new FileWriter(f2);
            fw.write(System.getProperty("java.class.path"));
            fw.close();
            String fgf = System.getProperty("os.name").contains("Windows") ? "\"" : "'";
            //  System.out.println(System.getProperty("os.name"));
            //  System.out.println(fgf + GameInfo.JavaPath + fgf + " -jar " + fgf + GameInfo.Rundir + tpf + "MCLaucherXA" + Updater.ver + ".jar" + fgf);
            Runtime.getRuntime().exec("\"" + GameInfo.JavaPath  + "\" -jar " + fgf + GameInfo.Rundir + tpf + "MCLaucherXA" + Updater.ver + ".jar" + fgf);
            System.exit(0);
            //      new File(System.getProperty("java.class.path")).deleteOnExit();
        } catch (IOException | HeadlessException ex) {
            JOptionPane.showMessageDialog(null, Lang.getLang("Up_DownFaild") + "\n" + ex, "", JOptionPane.ERROR_MESSAGE);
            b.setEnabled(true);
        }
    }
}
